import { Alias as S } from '../nodes/Alias.js';
import {
  isDocument as w,
  isNode as T,
  isPair as A,
  MAP as p,
  SEQ as B,
} from '../nodes/identity.js';
import { Scalar as j } from '../nodes/Scalar.js';
const P = 'tag:yaml.org,2002:';
function g(n, i, f) {
  if (i) {
    const t = f.filter(s => s.tag === i),
      e = t.find(s => !s.format) ?? t[0];
    if (!e) throw new Error(`Tag ${i} not found`);
    return e;
  }
  return f.find(t => {
    var e;
    return ((e = t.identify) == null ? void 0 : e.call(t, n)) && !t.format;
  });
}
function I(n, i, f) {
  var b, y, O;
  if ((w(n) && (n = n.contents), T(n))) return n;
  if (A(n)) {
    const c =
      (y = (b = f.schema[p]).createNode) == null
        ? void 0
        : y.call(b, f.schema, null, f);
    return c.items.push(n), c;
  }
  (n instanceof String ||
    n instanceof Number ||
    n instanceof Boolean ||
    (typeof BigInt < 'u' && n instanceof BigInt)) &&
    (n = n.valueOf());
  const {
    aliasDuplicateObjects: t,
    onAnchor: e,
    onTagObj: s,
    schema: d,
    sourceObjects: m,
  } = f;
  let r;
  if (t && n && typeof n == 'object') {
    if (((r = m.get(n)), r))
      return r.anchor || (r.anchor = e(n)), new S(r.anchor);
    (r = { anchor: null, node: null }), m.set(n, r);
  }
  i != null && i.startsWith('!!') && (i = P + i.slice(2));
  let o = g(n, i, d.tags);
  if (!o) {
    if (
      (n && typeof n.toJSON == 'function' && (n = n.toJSON()),
      !n || typeof n != 'object')
    ) {
      const c = new j(n);
      return r && (r.node = c), c;
    }
    o = n instanceof Map ? d[p] : Symbol.iterator in Object(n) ? d[B] : d[p];
  }
  s && (s(o), delete f.onTagObj);
  const h =
    o != null && o.createNode
      ? o.createNode(f.schema, n, f)
      : typeof ((O = o == null ? void 0 : o.nodeClass) == null
            ? void 0
            : O.from) == 'function'
        ? o.nodeClass.from(f.schema, n, f)
        : new j(n);
  return i ? (h.tag = i) : o.default || (h.tag = o.tag), r && (r.node = h), h;
}
export { I as createNode };
